<template>
	<view class="uni-container">
		<view class="cu-form-group margin-top">
			<view class="title">书名</view>
			<input placeholder="请输入书名" v-model="book_data.title"></input>
		</view>
		<view class="cu-form-group margin-top">
			<view class="title">作者</view>
			<input placeholder="请输入作者" v-model="book_data.author"></input>
		</view>
		<view class="cu-form-group margin-top">
			<view class="title">出版社</view>
			<input placeholder="请输入出版社" v-model="book_data.publishing_house"></input>
		</view>
		<view class="cu-form-group margin-top">
			<view class="title">ISBN</view>
			<input placeholder="请输入isbn" v-model="book_data.ISBN"></input>
		</view>
		<view class="cu-form-group margin-top">
			<view class="title">简介</view>
			<textarea placeholder="请输入图书简介" maxlength=-1 v-model="book_data.description"></textarea>
		</view>
		<view class="cu-form-group margin-top" @tap="showModal" data-target="bottomModal">
			<view class="title">存放位置</view>
			<input placeholder="楼层-书架编号-书架层(从上至下)" name="input" v-model='book_location' disabled=true></input>
		</view>
		<!-- 书架位置弹窗 -->
		<view class="cu-modal bottom-modal" :class="modalName=='bottomModal'?'show':''">
			<view class="cu-dialog bg-white">
				<view class="cu-bar bg-white">
					<view class="action text-blue" @tap="hideModal">取消</view>
					<view class="action text-green" @click="saveChoose">确定</view>
				</view>
				<picker-view indicator-style="height: 50px;" @change="PickerChange" :value="bookshelf_index" class="picker-view">
					<picker-view-column>
						<view class="item" v-for="(item,index) in bookshelf_floor" :key="index">{{item}}</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in bookshelf_num" :key="index">{{item}}</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in bookshelf_layer" :key="index">{{item}}</view>
					</picker-view-column>
				</picker-view>
			</view>
		</view>
		<!-- 图书封面图片 -->
		<view class="cu-bar bg-white margin-top">
			<view class="action">
				图片上传
			</view>
			<view class="action">
				{{imgList.length}}/1
			</view>
		</view>
		<view class="bg-white padding">
			<text class="gray">上传咨询封面照片，推荐横向图片</text>
		</view>
		<view cla
		<view class="cu-form-group padding">
			<view class="grid col-2 grid-square flex-sub">
				<view class="bg-img" @tap="ViewImage" data-index="0" v-if="imgList.length!=0">
					<image :src="imgList[0]" mode="aspectFill"></image>
					<view class="cu-tag bg-red" @tap.stop="DelImg" data-index="0">
						<text class='cuIcon-close'></text>
					</view>
				</view>
				<view class="solids" @tap="ChooseImage" v-if="imgList.length<1">
					<text class='cuIcon-cameraadd'></text>
				</view>
			</view>
		</view>

		<view class="grid justify-center margin-top">
			<button class="cu-btn round shadow bg-blue lg iconfont" @click="scanCode">&#xe600; 扫码</button>
			<button class="margin-left cu-btn round shadow bg-green iconfont lg" @click="submit(false)">&#xe61a; 提交</button>
		</view>
	</view>
</template>

<script>
	const db = uniCloud.database();
	const book_db = db.collection("library-books");
	import upFile from '@/common/uploadUtils.js'

	export default {
		data() {
			return {
				book_data: {},
				modalName: null,
				book_location: "",
				bookshelf_index: [0, 0, 0],
				bookshelf_floor: ["24", "25", "26", "27", "28", "29"],
				bookshelf_num: ["A", "B", "C", "D", "E", "F"],
				bookshelf_layer: ["1", "2", "3", "4", "5", "6", "7"],
				imgList: []
			}
		},
		methods: {
			scanCode: function() {
				var that = this
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['barCode'],
					success: (scan_res) => {
						uni.showLoading({
							title: "数据加载中"
						});
						this.book_data.ISBN = scan_res.result;
						uniCloud.callFunction({
							name: "downloadDoubanPic",
							data: {
								isbn: scan_res.result
							},
							success: (res) => {
								that.book_data = {
									author: res.result.author,
									title: res.result.title,
									publishing_house: res.result.publisher,
									description: res.result.summary,
									ISBN: res.result.isbn,
									book_id: "",
									book_thumb: "https://images.weserv.nl/?url=" + res.result.image.substring(7)
								}
								this.submit(true);
								uni.hideLoading();
							},
							fail: (err) => {
								uni.showToast({
									icon: "none",
									title: "扫码出错，请重新扫码或手动输入"
								})
							}
						});
					}
				});
			},
			/**
			 * 图片管理
			 */
			ChooseImage(e) {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths)
						} else {
							this.imgList = res.tempFilePaths
						}
						
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					content: '确定要删除这张照片吗？',
					cancelText: '再看看',
					confirmText: '再见',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			submit: function(scan) {
				
				var that = this;
				if (this.book_location == "") {
					uni.showModal({
						title: "请选择书本存放位置"
					})
				} else if (this.book_data.ISBN) {
					uni.showLoading({
						title: "上传中",
						mask: true
					})
					// 把book_id的前面部分拼凑出来
					var book_location_id = this.bookshelf_floor[this.bookshelf_index[0]] + "-";
					book_location_id += this.bookshelf_num[this.bookshelf_index[1]] + "-";
					book_location_id += this.bookshelf_layer[this.bookshelf_index[2]]
					if (scan) {
						book_db.where('ISBN=="' + this.book_data.ISBN + '"').get({
							getCount: true
						}).then(res => {
							if (res.result.count != 0) {
								uni.showModal({
									title: "已有相同图书，是否重复添加",
									success: (res) => {
										if (res.confirm) {
											this.storeBookDb(book_location_id);
										}
									}
								})
							} else if (res.result.count == 0) {
								this.storeBookDb(book_location_id);
							}
						}).catch((err) => {
							uni.showModal({
								content: err.message || '请求服务失败',
								showCancel: false
							})
						}).finally(() => {
							uni.hideLoading()
						})
					} else {
						var file_path = new Array();
						var value = this.book_data;
						var that = this;
						upFile.mutiupload(this.imgList, file_path ,0, this.imgList.length, value.title, function(file_path) {
							console.log(file_path[0])
							that.book_data["book_thumb"] = file_path[0];
							// 使用 clientDB 提交数据
							book_db.where('ISBN=="' + that.book_data.ISBN + '"').get({
								getCount: true
							}).then(res => {
								if (res.result.count != 0) {
									uni.showModal({
										title: "已有相同图书，是否重复添加",
										success: (res) => {
											if (res.confirm) {
												that.storeBookDb(book_location_id);
											}
										}
									})
								} else if (res.result.count == 0) {
									that.storeBookDb(book_location_id);
								}
							}).catch((err) => {
								uni.showModal({
									content: err.message || '请求服务失败',
									showCancel: false
								})
							}).finally(() => {
								uni.hideLoading()
							})
						})
					}
				}
			},

			previewPic: function(e) {
				uni.previewImage({
					urls: [this.imgPath]
				})
			},
			
			storeBookDb: function(book_location_id) {
				book_db.where('/' + book_location_id + '/.test(book_id)').get({
					getCount: true
				}).then(res => {
					// 改层书架已有书籍编号 +1
					// 前面自动补0
					var bookNum = ("000" + (res.result.count + 1)).slice(-3)
					this.book_data.book_id = book_location_id + "-" + bookNum
				}).then(() => {
					uni.hideLoading();
					book_db.add(this.book_data).then(() => {
						uni.showToast({
							title: "添加成功"
						});
						this.book_data = {};
						this.imgList = [];
					})
				})
			},

			// 存书位置选择器
			PickerChange(e) {
				const val = e.detail.value;
				this.bookshelf_index = val;
			},

			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},

			hideModal(e) {
				this.modalName = null
			},

			saveChoose(e) {
				// if (bookshelf_index)
				this.book_location = this.bookshelf_floor[this.bookshelf_index[0]] + "楼-";
				this.book_location += this.bookshelf_num[this.bookshelf_index[1]] + "书架-"
				this.book_location += this.bookshelf_layer[this.bookshelf_index[2]] + "层";

				this.modalName = null;
			},
		}
	}
</script>

<style>
	.picker-view {
		width: 750rpx;
		height: 600rpx;
		margin-top: 20rpx;
	}
</style>
